var express = require('express');
var router = express.Router();
const { UserModel } = require('../model/model');
const jwt = require('jsonwebtoken');
const SECRET_KEY = 'your_secret_key'; // 建议放到环境变量
const ACCESS_TOKEN_EXPIRES_IN = '15m';
const REFRESH_TOKEN_EXPIRES_IN = '7d';

// 内存存储refreshToken
const refreshTokens = new Set();

/* GET users listing. */
router.get('/', async function(req, res, next) {
  const { username, password } = req.query;
  if (!username || !password) {
    return res.status(400).json({ error: '缺少用户名或密码' });
  }
  try {
    const users = await UserModel.find({ username, password });
    res.json(users);
  } catch (err) {
    res.status(500).json({ error: '数据库查询失败' });
  }
});

// 登录接口（POST /users/login）
router.post('/login', async function(req, res) {
  const { username, password } = req.body;
  if (!username || !password) {
    return res.status(400).json({ error: '缺少用户名或密码' });
  }
  try {
    const user = await UserModel.findOne({ username, password });
    if (!user) {
      return res.status(401).json({ error: '用户名或密码错误' });
    }
    // 生成accessToken和refreshToken
    const accessToken = jwt.sign({ username }, SECRET_KEY, { expiresIn: ACCESS_TOKEN_EXPIRES_IN });
    const refreshToken = jwt.sign({ username }, SECRET_KEY, { expiresIn: REFRESH_TOKEN_EXPIRES_IN });
    refreshTokens.add(refreshToken);
    // 设置httpOnly cookie
    res.cookie('refreshToken', refreshToken, {
      httpOnly: true,
      maxAge: 7 * 24 * 60 * 60 * 1000 // 7天
    });
    // 返回accessToken
    res.json({ accessToken });
  } catch (err) {
    res.status(500).json({ error: '服务器错误' });
  }
});

// 刷新token接口（POST /users/refresh-token）
router.post('/refresh-token', (req, res) => {
  const refreshToken = req.cookies.refreshToken;
  if (!refreshToken) {
    return res.status(401).json({ error: '未提供refreshToken' });
  }
  if (!refreshTokens.has(refreshToken)) {
    return res.status(403).json({ error: 'refreshToken无效' });
  }
  try {
    const payload = jwt.verify(refreshToken, SECRET_KEY);
    const accessToken = jwt.sign({ username: payload.username }, SECRET_KEY, { expiresIn: ACCESS_TOKEN_EXPIRES_IN });
    res.json({ accessToken });
  } catch (err) {
    return res.status(403).json({ error: 'refreshToken已过期' });
  }
});

// 登出接口（可选，清除refreshToken）
router.post('/logout', (req, res) => {
  const refreshToken = req.cookies.refreshToken;
  if (refreshToken) {
    refreshTokens.delete(refreshToken);
    res.clearCookie('refreshToken');
  }
  res.json({ message: '登出成功' });
});

module.exports = router;
